﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin;
using BenCaoXuan.Infrastructure.Dto.Admin.promotion;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Promotion_Service : Base_Service, I_Promotion_Service
    {
        private readonly Product_IOC _product_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Login_IOC _login_IOC;

        public Promotion_Service(Customer_IOC customer_IOC,
            Login_IOC login_IOC,
            Product_IOC product_IOC)
        {
            _product_IOC = product_IOC;
            _customer_IOC = customer_IOC;
            _login_IOC = login_IOC;
        }

        /// <summary>
        /// 新增佣金规则
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Rules(AddRules_Dto dto)
        {
            //判断是否存在
            if (dto.productId != null) {
                var data =await _customer_IOC._commissionRules_EFCore.GetAll(d => d.CrProductId == dto.productId).SingleOrDefaultAsync();
                if (data != null)
                {
                    _customer_IOC._commissionRules_EFCore.Delete(data);
                    await _customer_IOC._commissionRules_EFCore.SaveChangesAsync();
                }
            }
            else if(dto.packageId!=null){
                var data = await _customer_IOC._commissionRules_EFCore.GetAll(d => d.CrPackageId == dto.packageId).SingleOrDefaultAsync();
                if (data != null)
                {
                    _customer_IOC._commissionRules_EFCore.Delete(data);
                    await _customer_IOC._commissionRules_EFCore.SaveChangesAsync();
                }
            }
            CommissionRule commissionRule = new CommissionRule() { 
            CrId=Config.GUID(),
            CrCount=5,
            CrCommissionRate=(decimal)dto.commissionRate!,
            CrCreateTime=DateTime.Now,
            CrDescription=dto.description,
            CrPackageId=dto.packageId,
            CrProductId=dto.productId,
            CrProductName=dto.productName,
            CrProductType=dto.productType,
            

            };

            _customer_IOC._commissionRules_EFCore.Add(commissionRule);
            var result = await _customer_IOC._commissionRules_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取推广数据
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Commission(Fenye_Dto dto)
        {
            var allcustomer = await _customer_IOC._customer_EFCore.GetAll().ToListAsync();
            var allemployee = await _login_IOC._sysEmployee_EFCore.GetAll().ToListAsync();

            var query = _customer_IOC._customerVipCpsCommission_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.CcvcCreateTime);

            if (!string.IsNullOrEmpty(dto.key))
            {
                var promoterIds = allcustomer
                    .Where(c => c.CName.Contains(dto.key))
                    .Select(c => c.CId)
                    .ToList();
                query = query.Where(d => promoterIds.Contains(d.CcvcPromoterId));
            }

            var data = await query
                .Select(d => new Commission_Dto
                {
                    id = d.CcvcId,
                    commissionStatus = d.CcvcCommissionStatus,
                    cps = d.CcvcCps,
                    commissionAmount=(double)d.CcvcCommissionAmount,
                    createTime = d.CcvcCreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    inviteeID = d.CcvcInviteeId,
                    operatorID = d.CcvcOperatorId,
                    promoterID = d.CcvcPromoterId,
                    releaseTime = d.CcvcReleaseTime.HasValue
                        ? d.CcvcReleaseTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                        : string.Empty,
                    remark = d.CcvcRemark,
                    triggerType=d.CcvcTriggerType==1? "被邀请人注册": "被邀请人消费"


                })
                .ToListAsync();

            data.ForEach(d =>
            {
                d.invitee = allcustomer.FirstOrDefault(c => c.CId == d.inviteeID)?.CName;
                d.promoter = allcustomer.FirstOrDefault(c => c.CId == d.promoterID)?.CName;
                d.employeeName = allemployee.FirstOrDefault(c => c.EId == d.operatorID)?.EName;
            });

            return Get_Result(0, "ok", new { data, total });
        }

        /// <summary>
        /// 通过规则类型获取对应的产品
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_ProductByRulesType(int? value)
        {
            if (value == 0) {
                //服务
                var data =await _product_IOC._product_EFCore.GetAll()
                    .Select(d => new PromotionProduct_Dto{ 
                    label=d.PName,
                    value=d.PId
                    }).ToListAsync();

                return Get_Result(0, "ok", data);
            
            } else 
            if(value==1){
                //套餐

                var data =await _product_IOC._productPackage_EFCore.GetAll()
                    .Select(d => new PromotionProduct_Dto { 
                    label=d.PpName,
                    value=d.PpId
                    }).ToListAsync();
                return Get_Result(0, "ok", data);
            }

            return Get_Result(0, "ok");
        }

        /// <summary>
        /// 获取佣金规则
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Rules()
        {
            //获取
            var data =await _customer_IOC._commissionRules_EFCore.GetAll()
                .Select(d => new Rules_Dto{
                    id=d.CrId,
                    commissionRate=d.CrCommissionRate+"%",
                    count=d.CrCount,
                    description=d.CrDescription,
                    packageId=d.CrPackageId,
                    productId=d.CrProductId,
                    productName=d.CrProductName,
                    productType=d.CrProductType,

                }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 发放佣金
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Grant_Commission(string? id, string? employeeID)
        {
            var data =await _customer_IOC._customerVipCpsCommission_EFCore.GetAll(d => d.CcvcId == id).SingleAsync();
            data.CcvcCommissionStatus = 2;
            data.CcvcOperatorId = employeeID;
            data.CcvcUpdateTime= DateTime.Now;
            data.CcvcReleaseTime = DateTime.Now;
            _customer_IOC._customerVipCpsCommission_EFCore.Update(data);
            var result = await _customer_IOC._customerVipCpsCommission_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 编辑佣金规则
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Rules(UpdateRules_Dto dto)
        {
            var data =await _customer_IOC._commissionRules_EFCore.GetAll(d => d.CrId == dto.id).SingleAsync();
            data.CrDescription = dto.serviceDesc;
            data.CrCommissionRate =(decimal)dto.commissionRate!;
            _customer_IOC._commissionRules_EFCore.Update(data);
            var result = await _customer_IOC._commissionRules_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }
    }
}
